﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DH.Web.Controllers;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using DH.Service.Domain;
using Microsoft.AspNetCore.Authorization;
using DH.Web.Attributes;
using DH.Core;
using Newtonsoft.Json;
using DH.Web.MVC.Extensions;
using DH.Web.Filter;
using System.ComponentModel;
using DH.Core.Helper;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("Button")]
    [Resource("按钮(资源)")]
    [Guid("0e16384e-1fc8-4e18-b6b1-b7f69062fa41")]
    public class ButtonController : SiteController<ButtonEntity, ButtonViewModel, string>
    {
        protected ButtonService _buttonService;
        
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public ButtonController(IServiceCollection serviceCollection,
                              ButtonService buttonService) : base(serviceCollection, buttonService)
        {
            _buttonService = buttonService;
            
        }

        [HttpGet]
        [Route("Index")]
        [UIView("按钮管理首页")]
        [Guid("ed29eaf6-8d30-45dd-bd17-6c8427477535")]
        public IActionResult Index()
        {
            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "ed29eaf6-8d30-45dd-bd17-6c8427477535";
            return View();
        }


        [HttpGet]
        [Route("Buttons")]
        [Function("获取按钮列表")]
        [Guid("91bd5ea3-f024-497a-bd93-f5baad6fa3d5")]
        public async Task<IActionResult> GetRoleList()
        {
            PagedData<ButtonViewModel> models;
            var pagination = GetPagination();
            var queryKey = Request.Query["queryKey"][0];

            var filterObj = new ButtonQueryDto();
            var filter = Request.Query["filter"];
            if (filter.Any())
            {
                if (filter[0] != "")
                {
                    filterObj = JsonConvert.DeserializeObject<ButtonQueryDto>(filter[0]);
                }

            }

            var res =await _buttonService.GetList(queryKey, filterObj, pagination);
            models = res.ToViewModelPageData<ButtonEntity, ButtonViewModel>();

            var result = new { total = models.TotalCount, rows = models.DataList };
            return Json(result);
        }

        [HttpPost]
        [Route("Add")]
        [UserPermissionFilter]
        [Function("添加/编辑按钮", isManage: true)]
        [Guid("13805578-09e3-4624-9b51-00b1cd7f3f64")]
        ///<summary>
        ///添加编辑角色
        ///受系统托管
        ///</summary>
        public async Task<IActionResult> AddButton(ButtonViewModel input)
        {
            if (!ModelState.IsValid)
            {
                return ErrorMessage("实体类验证失败");
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(input.Id))
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.UpdatedOn = DateTimeOffset.Now;

                    await _buttonService.EditAsync(input);
                }
                else
                {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;
                    input.Id = Guid.NewGuid().ToString();
                    input.CategoryCode = ConstHelper.ButtonType;
                    await _buttonService.AddAsync(input);
                }

                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("新增/编辑 按钮时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while add/edit button : {0}", nameof(RoleViewModel));
            }

        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Delete")]
        [Function("删除按钮", isManage: true)]
        [Guid("dae8db39-0ccf-49d2-b639-db932fb8cf4f")]
        ///<summary>
        ///删除
        ///受系统托管
        ///</summary>
        public async Task<IActionResult> Delete(string[] ids)
        {
            try
            {
                await _buttonService.DeleteAsync(ids);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除按钮时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while deleting button with id: {0}", ids);
            }
        }

        [HttpPost]
        [Route("EnableButton")]
        [Function("启用按钮", isManage: true)]
        [Description("启用按钮")]
        [Guid("321b4d93-2b1a-41c2-95b0-3074f9b60abe")]
        public async Task<IActionResult> EnableButton(string id)
        {
            try
            {
                await _buttonService.EnabledAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("启用按钮时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while enable button with id: {0}", id);
            }
        }

        [HttpPost]
        [Route("DisAbleButton")]
        [Function("禁用按钮", isManage: true)]
        [Description("禁用按钮")]
        [Guid("b9c74361-9d2f-445c-b24f-739cced6fdc2")]
        public async Task<IActionResult> DisAbleRole(string id)
        {
            try
            {
                await _buttonService.DisabledAsync(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("禁用按钮时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while disabling button with id: {0}", id);
            }
        }

        [HttpGet]
        [Route("GetButtons")]
        [Function("获取按钮集合")]
        [Description("获取按钮集合")]
        [Guid("12bcff5a-0c41-4c12-b9c6-026a27f4b34e")]
        public async Task<IActionResult> GetButtons()
        {
            var res = await _buttonService.GetButtonsRelevancesAsync(true);
            
            return new JsonResult(res);
        }

        

    }
}